package com.henry.utils;
 
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * @author Henry Guan
 * @description 生成随机验证码
 * @since 2023-08-31
 */
public class RandomUtil {
 
    private static final Random random = new Random();
 
    private static final DecimalFormat fourDf = new DecimalFormat("0000");
 
    private static final DecimalFormat sixDf = new DecimalFormat("000000");
 
    public static String getFourBitRandom() {
        return fourDf.format(random.nextInt(10000));
    }
 
    public static String getSixBitRandom() {
        return sixDf.format(random.nextInt(1000000));
    }
 
    /**
     * 给定数组，抽取n个数据
     */
    public static ArrayList<Object> getRandom(List<Object> list, int n) {
 
        Random random = new Random();
 
        HashMap<Object, Object> hashMap = new HashMap<>();
 
        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {
 
            int number = random.nextInt(100) + 1;
 
            hashMap.put(number, i);
        }
 
        // 从HashMap导入数组
        Object[] rObjs = hashMap.values().toArray();
 
        ArrayList<Object> r = new ArrayList<>();
 
        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) rObjs[i]));
            System.out.print(list.get((int) rObjs[i]) + "\t");
        }
        System.out.print("\n");
        return r;
    }
 
}